package com.ruoyi.project.h265;

import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avformat;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.*;

public class H265ToRtmp {
    public static void main(String[] args) throws Exception {
        /*// 输入文件路径
        String inputFile = "C:\\Users\\admin\\Desktop\\视频相机测试工具\\码流测试工具\\stream-0.h265";
        // 输出流地址
        String rtmpUrl = "rtmp://iot-test.wiot.tech:1017/myapp/stream66";

        // 初始化FFmpegFrameGrabber和FFmpegFrameRecorder
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
        grabber.setFormat("h265");
        grabber.start();
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(rtmpUrl, grabber.getImageWidth(), grabber.getImageHeight());
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
        recorder.setFormat("flv");
        recorder.setFrameRate(grabber.getFrameRate());
        recorder.start();

        // 开始转换
        Frame frame = null;
        while ((frame = grabber.grab()) != null) {
            recorder.record(frame);
        }

        // 释放资源
        recorder.stop();
        recorder.release();
        grabber.stop();
        grabber.release();*/

        // 创建FrameGrabber对象，用于捕获图像或视频
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber("C:\\Users\\admin\\Desktop\\视频相机测试工具\\trailer.mp4");
//        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber("rtsp://10.1.14.75:8554/main");
        grabber.setOption("rtsp_transport", "tcp");
//        grabber.setOption("probesize", "1024*20");
        grabber.setFrameRate(30);
        grabber.setVideoBitrate(2000000);
        grabber.start();

        // 创建FFmpegFrameRecorder对象，用于将图像或视频写入rtmp流
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("rtmp://192.168.33.207:1935/myapp/stream22", grabber.getImageWidth(), grabber.getImageHeight());
        recorder.setInterleaved(true);
        recorder.setVideoOption("tune", "zerolatency");
        recorder.setVideoOption("preset", "ultrafast");
        recorder.setVideoOption("crf", "28");
        recorder.setVideoBitrate(2000000);//码率 越大越清晰
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
        recorder.setFormat("flv");//flv rtsp
        recorder.setFrameRate(30);//帧率 30fps 每秒包含的帧数 24-30越大越流畅
        recorder.setGopSize(1);//30*2 每60帧存在一个关键帧
        recorder.setOption("flvflags","no_duration_filesize");
//        recorder.setOption("stream_loop","-1");
        recorder.start();

        // 读取图像或视频帧，并将其写入rtmp流
        Frame frame;
        while ((frame = grabber.grab()) != null) {
            recorder.record(frame);
        }

        // 停止抓取和录制
        recorder.stop();
        recorder.release();
        grabber.stop();
        grabber.release();

    }
}

